package com.wz.jiangsu.main.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: wz
 * @author: wangzhou
 * @create: 2024-08-12 14:13
 * @description:
 **/
@Slf4j
public class TestReentrantLock2 {
    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws Exception {
        new Thread(() -> {

            try {
                lock.lock();
                log.debug("--------------- t2 线程获取锁，然后去睡了 5s");
                TimeUnit.SECONDS.sleep(5L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                log.debug("t2 线程进行释放锁");
                lock.unlock();
            }
        }, "t2").start();

        /**主线程main睡2秒，然后创建线程 t1 */
        TimeUnit.SECONDS.sleep(2); //此处主线程睡眠主要为了确保t2先拿到锁，实现效果

        Thread t1 = new Thread(() -> {

            try {
                lock.lockInterruptibly();
                log.debug("--------------- t1 获取到了锁");
            } catch (InterruptedException e) {
                log.debug("---------------t1 被主线程打断了，没有获取到锁 -----------------");
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }, "t1");

        t1.start();

        // 主线程睡完了 2秒之后醒来，打断 t1
        log.debug("-----------------主线程睡完了2s 之后醒来，打断t1---------");
        t1.interrupt();
    }
}
